package study.远程调用;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
/**
 * @Author 刘伟涛
 * @Date 2024/6/13 14:29
 **/
public class FormDateStyle {
    public static void main(String[] args) {
        try {
            // 目标URL
            URL url = new URL("http://218.17.50.150:6610/biz/equipmentPoint/findEquipmentListByTreeId");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();

            // 设置请求方法为POST
            connection.setRequestMethod("POST");
            // 设置请求头
            connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            connection.setRequestProperty("token", "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiIxfDE3MTgzNDEyMjQyODEiLCJpYXQiOjE3MTgzNDEyMjQsImV4cCI6MTcxOTIwNTIyNH0.JSkVqOLcoKZLYW41wAebnW2d6lboUoMEj6UWFxtwuPFozIcyfTQS7pLm_guhl0ge66esY6XmxtiFYad5rXiFcw");
            connection.setDoOutput(true);  // 允许写入数据

            // 表单数据
            String formData = "thingKey=001000000000";

            // 发送数据
            try (OutputStream os = connection.getOutputStream()) {
                byte[] input = formData.getBytes(StandardCharsets.UTF_8);
                os.write(input, 0, input.length);
            }

            // 获取响应
            int responseCode = connection.getResponseCode();

            System.out.println("响应代码: " + responseCode);
            if (responseCode == HttpURLConnection.HTTP_OK) {
                System.out.println("请求成功！");
                InputStream inputStream;
                if (responseCode >= 200 && responseCode < 300) {
                    inputStream = connection.getInputStream();
                } else {
                    inputStream = connection.getErrorStream();
                }

                // 读取响应内容
                String responseContent = readStream(inputStream);
                System.out.println("响应内容: " + responseContent);


            } else {
                System.out.println("请求失败，状态码: " + responseCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 工具方法，将输入流读取为字符串
    private static String readStream(InputStream stream) {
        StringBuilder response = new StringBuilder();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) {
            String line;
            while ((line = reader.readLine()) != null) {
                response.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response.toString();
    }
}
